<template>
  <div>
    <!-- 手机端上传组件 -->
    <el-upload
      ref="upload"
      :auto-upload="false"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :show-file-list="false"
      accept="image/*"
      action="/api/upload"
      class="upload-demo"
    >
      <el-button slot="trigger" size="small" type="primary">选择图片</el-button>
    </el-upload>
  </div>
</template>

<script>
import io from 'socket.io-client';

export default {
  methods: {
    beforeUpload(file) {
      debugger
      // 若依可能需要添加 Token 认证
      const token = localStorage.getItem('token')
      if (token) {
        this.$refs.upload.setRequestHeader('Authorization', `Bearer ${token}`)
      }
      return true
    },
    handleSuccess(response, file) {
      if (response.code === 200) {
        this.$socket.emit('image-uploaded', response.data.url)
      }
    }
  },
  mounted() {
    // 初始化 WebSocket 连接
    this.$socket = io('http://localhost:8080/ws')
  }
}
</script>
